"use strict";

const db = uniCloud.database();
const friendsCollection = db.collection("nearby-friends");
const $ = db.command.aggregate;
const _ = db.command;

// 计算两点之间的距离（米）
const calculateDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371000; // 地球半径，单位米
  const dLat = ((lat2 - lat1) * Math.PI) / 180;
  const dLon = ((lon2 - lon1) * Math.PI) / 180;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos((lat1 * Math.PI) / 180) *
      Math.cos((lat2 * Math.PI) / 180) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
};

exports.main = async (event, context) => {
  const { action, data, uniIdToken } = event;

  // 获取用户身份信息
  let userInfo;
  try {
    const uniID = require("uni-id-common");
    const idInstance = uniID.createInstance({ context });
    userInfo = await idInstance.checkToken(uniIdToken);
    if (userInfo.code !== 0) {
      return { code: 401, message: "未授权，请登录后操作" };
    }
  } catch (e) {
    return { code: 502, message: "服务器异常" };
  }

  const userId = userInfo.uid;

  switch (action) {
    // 更新当前位置
    case "updateLocation": {
      try {
        const { latitude, longitude } = data;

        if (!latitude || !longitude) {
          return { code: 400, message: "位置信息不完整" };
        }

        // 检查是否已有记录
        const existingRecord = await friendsCollection
          .where({
            user_id: userId,
          })
          .get();

        const updateData = {
          user_id: userId,
          name:
            userInfo.userInfo.nickname ||
            userInfo.userInfo.username ||
            "用户" + userId.substring(0, 6),
          avatar: userInfo.userInfo.avatar || "/static/default-avatar.png",
          latitude,
          longitude,
          last_update: new Date(),
          status: "online",
        };

        let result;
        if (existingRecord.data.length > 0) {
          // 更新已有记录
          result = await friendsCollection
            .where({
              user_id: userId,
            })
            .update(updateData);
        } else {
          // 创建新记录
          result = await friendsCollection.add(updateData);
        }

        return { code: 0, message: "位置已更新" };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "更新位置失败" };
      }
    }

    // 获取附近同伴
    case "getNearbyFriends": {
      try {
        const { latitude, longitude, distance = 5000 } = data; // 默认5公里内

        if (!latitude || !longitude) {
          return { code: 400, message: "位置信息不完整" };
        }

        // 先更新自己的位置
        await friendsCollection
          .where({
            user_id: userId,
          })
          .update({
            latitude,
            longitude,
            last_update: new Date(),
            status: "online",
          });

        // 计算位置矩形范围
        // 每0.01度约等于1.1公里，保守估算
        const distanceDegree = distance / 111000;

        // 找出范围内的同伴 (排除自己)
        const result = await friendsCollection
          .where({
            user_id: _.neq(userId),
            latitude: _.gt(latitude - distanceDegree).and(
              _.lt(latitude + distanceDegree)
            ),
            longitude: _.gt(longitude - distanceDegree).and(
              _.lt(longitude + distanceDegree)
            ),
            // 只显示30分钟内在线的用户
            last_update: _.gt(new Date(Date.now() - 30 * 60 * 1000)),
          })
          .get();

        // 计算实际距离并筛选
        const nearbyFriends = result.data
          .map((friend) => {
            const dist = calculateDistance(
              latitude,
              longitude,
              friend.latitude,
              friend.longitude
            );

            return {
              id: friend._id,
              user_id: friend.user_id,
              name: friend.name,
              avatar: friend.avatar,
              latitude: friend.latitude,
              longitude: friend.longitude,
              distance: dist,
              status: friend.status,
              last_update: friend.last_update,
            };
          })
          .filter((friend) => friend.distance <= distance)
          .sort((a, b) => a.distance - b.distance);

        return {
          code: 0,
          message: "获取附近同伴成功",
          data: nearbyFriends,
        };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "获取附近同伴失败" };
      }
    }

    // 设置在线状态
    case "setStatus": {
      try {
        const { status } = data;

        await friendsCollection
          .where({
            user_id: userId,
          })
          .update({
            status,
            last_update: new Date(),
          });

        return { code: 0, message: "状态已更新" };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "更新状态失败" };
      }
    }

    default:
      return { code: 400, message: "无效的操作类型" };
  }
};
